/**
*   \file   segmenttopoint.h
*   \author Dave Reid
*   \brief  Header file for finding the closest point on a line to another point.
*/
#ifndef __EAGL_CLOSESTPOINT_SEGMENTTOPOINT_H_
#define __EAGL_CLOSESTPOINT_SEGMENTTOPOINT_H_

#include "../types.h"

namespace eagl
{

inline vec3 closestpoint_segmenttopoint(const vec3 &segmentStart, const vec3 &segmentEnd, const vec3 &point)
{
    // Based off dist_Point_To_Segment() from:
	//     http://www.geometryalgorithms.com/Archive/algorithm_0102/algorithm_0102.htm#Distance%20to%20Ray%20or%20Segment

	vec3 segment(segmentEnd - segmentStart);
	vec3 segment_to_point(point - segmentStart);

    float c1 = glm::dot(segment_to_point, segment);
	if (c1 <= 0.0f)
	{
		return segmentStart;
	}

	float c2 = glm::dot(segment, segment);
	if (c2 <= c1)
	{
		return segmentEnd;
	}

	return segmentStart + ((c1 / c2) * segment);
}

inline vec2 closestpoint_segmenttopoint(const vec2 &segmentStart, const vec2 &segmentEnd, const vec2 &point)
{
    // Same as above.

    vec2 segment(segmentEnd - segmentStart);
	vec2 segment_to_point(point - segmentStart);

	float c1 = glm::dot(segment_to_point, segment);
	if (c1 <= 0.0f)
	{
		return segmentStart;
	}

	float c2 = glm::dot(segment, segment);
	if (c2 <= c1)
	{
		return segmentEnd;
	}

	return segmentStart + ((c1 / c2) * segment);
}

}

#endif  // __EAGL_CLOSESTPOINT_SEGMENTTOPOINT_H_